package cn.symbio.org.service.impl;

import cn.symbio.basic.service.impl.BaseServiceImpl;
import cn.symbio.basic.util.MD5Utils;
import cn.symbio.basic.util.PageList;
import cn.symbio.basic.util.StrUtils;
import cn.symbio.org.domain.Employee;
import cn.symbio.org.mapper.EmployeeMapper;
import cn.symbio.org.query.EmployeeQuery;
import cn.symbio.org.service.IEmployeeService;
import cn.symbio.user.domain.Logininfo;
import cn.symbio.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    public List<Employee> findEmpByDeptId(Long id) {
        return employeeMapper.findEmpByDeptId(id);
    }

    @Override
    public Employee findByLoginId(Long id) {
        return employeeMapper.findByLoginId(id);
    }

    @Override
    public List<Employee> SMMsg(Long shopId) {
        return employeeMapper.findByShopId(shopId);
    }


    @Override
    public void add(Employee employee) {
        // 盐值
        String s = StrUtils.getComplexRandomString(32);
        // 密
        String password = employee.getPassword();
        // md5加盐加密
        String md = MD5Utils.encrypByMd5(s + password);
        employee.setSalt(s);
        employee.setPassword(md);
        // logininfo添加数据
        Logininfo logininfo = this.logininfoCopyEmp(employee);
        logininfoMapper.add(logininfo);
        // 添加logininfo_id
        employee.setLogininfoId(logininfo.getId());
        super.add(employee);
    }


    @Override
    public void update(Employee employee) {

        // 获取emp数据用于获取logininfo_id
        Employee byIdEmp = employeeMapper.findById(employee.getId());
        // 获取去最新数据
        Logininfo logininfoCopyEmp = this.logininfoCopyEmp(employee);
        //设置logininfo_id
        logininfoCopyEmp.setId(byIdEmp.getLogininfoId());
        // logininfo添加数据
        logininfoMapper.update(logininfoCopyEmp);
        super.update(employee);
    }


    @Override
    public void delete(Long id) {
        // 根据getLogininfoId删除
        Employee byId = employeeMapper.findById(id);
        logininfoMapper.delete(byId.getLogininfoId());
        super.delete(id);
    }

    // 数据拷贝
    public Logininfo logininfoCopyEmp(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        return logininfo;
    }

}
